package image

import (
	"context"
	"fmt"
	"github.com/Unixeno/islands/cmd/connection"
	"github.com/Unixeno/islands/pb"
	"github.com/spf13/cobra"
	"path/filepath"
)

var outPath string

func GetImageExportCmd() *cobra.Command {
	imageExportCmd := &cobra.Command{
		Use:   "export id --output [tarfile]",
		Short: "export the image",
		Long:  `export specific image in your repo`,
		Args:  cobra.MinimumNArgs(1),
		Run:   imageExportHandle,
	}
	imageExportCmd.Flags().StringVar(&outPath, "output", "", "Tar file generated by the image")
	return imageExportCmd
}

func imageExportHandle(cmd *cobra.Command, args []string) {
	if len(args) < 1 || outPath == "" {
		_ = cmd.Help()
	} else {
		dir, file := filepath.Split(outPath)
		absDir, err := filepath.Abs(dir)
		if err != nil {
			fmt.Println(err.Error())
		}
		outPath = filepath.Join(absDir, file)
		id := CheckNameOrId(args[0])
		_, err = connection.Client.ExportImage(context.Background(), &pb.ExportImageReq{Id: id, TarFile: outPath})
		if err != nil {
			fmt.Println(err.Error())
		}
	}
}

